package com.mall.common.controller;

import static com.mall.common.bean.WebErrors.ERROR_ATTR_NAME;

import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.security.auth.login.AccountExpiredException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.mall.b2c.util.SettingUtils;
import com.mall.common.CommonSetting;
import com.mall.common.bean.User;
import com.mall.common.domain.manage.S_userDomain;
import com.mall.common.service.MenuService;
import com.mall.common.service.S_userService;
import com.mall.common.util.AppContext;
import com.mall.common.util.CacheUtils;
import com.mall.common.util.CommonSettingUtils;
import com.mall.common.util.ResponseUtils;

/**
 * 后台Action类 - 首页
 */
@Controller
@RequestMapping("/admin")
public class IndexController extends BaseController {

	public static final String SPRING_SECURITY_LAST_EXCEPTION = "SPRING_SECURITY_LAST_EXCEPTION";// Spring security 最后登录异常Session名称
	@Resource private S_userService s_userService;
	@Resource private MenuService menuService;

	@RequestMapping(value="/index", method=RequestMethod.GET)
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
		User user = getUser();
		if(user == null){
			return "redirect:/admin/login.jhtml";
		}
		model.addAttribute("user", user);
		model.addAttribute("setting", CommonSettingUtils.get());
		return "/admin/common/index";
	}

	@RequestMapping(value="/middle", method=RequestMethod.GET)
	public String middle(){
		return "/admin/common/middle";
	}
	
	@RequestMapping(value="/welcome", method=RequestMethod.GET)
	public String welcome(Model model) {
		S_userDomain user = s_userService.find(getUserId());
		model.addAttribute("user", user);
		model.addAttribute("setting", CommonSettingUtils.get());
		return "/admin/common/welcome";
	}
	
	// 登录页面
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login(Model model, HttpServletRequest request, HttpSession session) {
		//在登录界面中生成captchaid
		String captchaId = UUID.randomUUID().toString();
		model.addAttribute("captchaId", captchaId);
		String error = request.getParameter("error");
		if (StringUtils.endsWithIgnoreCase(error, "captcha")) {
			model.addAttribute("error", session.getAttribute("captchaError") != null?"验证码错误,请重新输入!":"");
			session.removeAttribute("captchaError");
			return "/admin/common/login";
		}
		Exception springSecurityLastException = (Exception) session.getAttribute(SPRING_SECURITY_LAST_EXCEPTION);
		if (springSecurityLastException != null) {
			if (springSecurityLastException instanceof BadCredentialsException) {
				String loginUsername = ((String) session.getAttribute("SPRING_SECURITY_LAST_USERNAME")).toLowerCase();
				S_userDomain admin = s_userService.get("username", loginUsername);
				if (admin != null) {
					CommonSetting setting = CommonSettingUtils.get();
					int loginFailureLockCount = setting.getAdminLoginFailureLockCount();
					int loginFailureCount = admin.getLoginFailureCount();
					if (setting.getIsAdminLoginFailureLock() && loginFailureLockCount - loginFailureCount <= 3) {
						model.addAttribute("error", "若连续" + loginFailureLockCount + "次密码输入错误,您的账号将被锁定!");
					} else {
						model.addAttribute("error", "您的用户名或密码错误!");
					}
				} else {
					model.addAttribute("error", "您的用户名或密码错误!");
				}
			} else if (springSecurityLastException instanceof DisabledException) {
				model.addAttribute("error", "您的账号已被禁用,无法登录!");
			} else if (springSecurityLastException instanceof LockedException) {
				model.addAttribute("error", "您的账号已被锁定,无法登录!");
			} else if (springSecurityLastException instanceof AccountExpiredException) {
				model.addAttribute("error", "您的账号已过期,无法登录!");
			} else {
				model.addAttribute("error", "出现未知错误,无法登录!");
			}
			session.removeAttribute(SPRING_SECURITY_LAST_EXCEPTION);
		}
		return "/admin/common/login";
	}
	
	/**
	 * 报表查询
	 * @param reportName 报表名称
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/report/{reportName}")
	public ModelAndView report(@PathVariable String reportName, HttpServletRequest request, ModelMap model){
		Map<String, String[]> map = request.getParameterMap();
		for(String key : map.keySet()){
			model.addAttribute(key, request.getParameter(key));
		}
		AppContext.setSessionAttr("report_" + reportName, true);
		model.addAttribute("__report", reportName + ".rptdesign");
		return new ModelAndView("redirect:/run", model);
	}

	/**
	 * 清除缓存
	 */
	@RequestMapping(value="/cleanCache",method=RequestMethod.POST)
	public void cleanCache(HttpServletResponse response){
		CacheUtils.clearCache(null);
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(SettingUtils.get().getUrlBuff(true).append("/cleanPageCache.jhtml").toString());
		try {
			httpClient.executeMethod(getMethod);
			ResponseUtils.renderJSON(successMessage, response);
		} catch (Exception e) {
			ResponseUtils.renderJSON(errorMessage, response);
		}
	}
	
	/**
	 * 后台错误页面
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/error")
	public String error(HttpServletRequest request, RedirectAttributes redirectAttributes){
		RequestAttributes requestattributes = RequestContextHolder.currentRequestAttributes();
		requestattributes.setAttribute("errors", request.getAttribute(ERROR_ATTR_NAME), 0);
		return "/admin/common/error";
	}
	
}